﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Collections.ObjectModel;
using MReviewerClient.MReviewerSvc;
using MReviewerClient.Models;
using System.Windows.Navigation;
using MReviewerClient.Providers;

namespace MReviewerClient.Views
{
    public partial class AddReviewDetailView : PhoneApplicationPage
    {
        #region Fields

        /// <summary>
        /// The selected Establishment
        /// </summary>
        public EstablishmentDTO SelectedEstablishment { get; set; }

        /// <summary>
        /// The list of Review
        /// </summary>
        public ObservableCollection<MealTypeDTO> MealTypes { get; set; }

        /// <summary>
        /// DateTime now
        /// </summary>
        public DateTime DateTimeNow { get; set; }

        #endregion

        #region Constructor

        /// <summary>
        /// The default constructor
        /// </summary>
        public AddReviewDetailView()
        {
            InitializeComponent();
        }

        #endregion

        #region Methods & Handlers

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            string id = NavigationContext.QueryString["id"];
            this.SelectedEstablishment = EstablishmentModel.Instance.SelectByID(id);

            MReviewerService.Instance.Review_SelectByEstablismentCompleted += Review_SelectByEstablismentCompletedHandler;
            MReviewerService.Instance.Review_SelectByEstablismentAsync(id);
        }

        private void Review_SelectByEstablismentCompletedHandler(object sender, Review_SelectByEstablismentCompletedEventArgs e)
        {
            ReviewModel.Instance.Reviews = e.Result;
            this.MealTypes = MealTypeModel.Instance.MealTypes;
            this.DateTimeNow = DateTime.Now;
            this.DataContext = this;
            MReviewerService.Instance.Review_SelectByEstablismentCompleted -= Review_SelectByEstablismentCompletedHandler;
        }

        /// <summary>
        /// Input validation
        /// </summary>
        /// <param name="errTxt"></param>
        /// <returns></returns>
        private bool ValidateUserInput(ref string errTxt)
        {
            // Meal Cost
            if (txtMealCost.Text.NonEquals(string.Empty) && txtMealCost.Text.IsNumeric() == false)
            {
                errTxt = "The Meal Cost input is invald numeric";
                return false;
            }

            // Service Rating
            if (txtServiceRating.Text.Equals(string.Empty))
            {
                errTxt = "Please input the Service Rating";
                return false;
            }
            else if(txtServiceRating.Text.IsNumeric() == false)
            {
                errTxt = "The Service Rating input is invald numeric";
                return false;
            }

            // AtmosphereRating
            if (txtAtmosphereRating.Text.Equals(string.Empty))
            {
                errTxt = "Please input the Atmosphere Rating";
                return false;
            }
            else if (txtAtmosphereRating.Text.IsNumeric() == false)
            {
                errTxt = "The Atmosphere Rating input is invald numeric";
                return false;
            }

            // FoodRating
            if (txtFoodRating.Text.Equals(string.Empty))
            {
                errTxt = "Please input the Food Rating";
                return false;
            }
            else if (txtFoodRating.Text.IsNumeric() == false)
            {
                errTxt = "The Food Rating input is invald numeric";
                return false;
            }

            return true;
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            var errTxt = string.Empty;
            if (this.ValidateUserInput(ref errTxt) == false)
            {
                MessageBox.Show(errTxt, "Error", MessageBoxButton.OK);
                return;
            }

            var item = new ReviewDTO
            {
                IDEstablishment = this.SelectedEstablishment.ID,
                IDMealType = (lstMealType.SelectedItem as MealTypeDTO).ID,
                ReviewDate = DateTime.Now,
                ServiceRating = double.Parse(txtServiceRating.Text),
                AtmosphereRating = double.Parse(txtAtmosphereRating.Text),
                FoodRating = double.Parse(txtFoodRating.Text),
                TitleComment = txtTitleComment.Text,
                ContentComment = txtContentComment.Text
            };

            if (txtMealCost.Text.NonEquals(string.Empty) && txtMealCost.Text.IsNumeric())
                item.MealCost = double.Parse(txtMealCost.Text);

            item.OverallRating = Math.Round((item.ServiceRating + item.AtmosphereRating + item.FoodRating) / 3, 2);

            // This action will be executed when the operation for selecting from service is completely
            Action actionInformResult = () =>
            {
                if (ReviewModel.Instance.InsertResult)
                {
                    MessageBox.Show("The new review for selected establishment has been added", "Information", MessageBoxButton.OK);
                    NavigationService.Navigate(new Uri(string.Format("/Views/ListAllReviewView.xaml?id={0}",
                        this.SelectedEstablishment.ID), UriKind.RelativeOrAbsolute));
                }
                else
                {
                    MessageBox.Show("Cannot insert the new review for selected establishment!", "Error", MessageBoxButton.OK);
                }

            };
            // Start to insert new review
            ReviewModel.Instance.Insert(item, actionInformResult);
        }

        #endregion
    }
}